<script setup lang="ts">
import { ref, watch, onMounted, toRaw } from 'vue'
import { postWorkflowTemplate, updateWorkflowTemplate } from '@/api/examples'
import { findUsers } from '@/api/permission'
import SytPageEditor from '@/components/SytPageEditor/SytPageEditor.ts'
import SytFlow from '@/components/SytFlow/SytFlow.vue'
import { ElMessage, ElButton } from 'element-plus'

const props = defineProps({
  data: {
    type: Object,
    default() {
      return {
        name: '',
        formData: '',
        flowData: {
          nodesData: [],
          linesData: []
        }
      }
    }
  }
})

const emit = defineEmits(['submit'])

const templateData = ref()

watch(
  () => props.data,
  () => {
    templateData.value = structuredClone(toRaw(props.data))
  },
  {
    immediate: true
  }
)

const formEditorRef = ref()

const onFormEditorChange = (pageStr, allPagesStr) => {
  templateData.value.formData = allPagesStr
}

const submitTemplate = async () => {
  if (!templateData.value.name) {
    ElMessage.error('模板名不能为空')
    return false
  }

  if (!templateData.value._id) await postWorkflowTemplate(templateData.value)
  else await updateWorkflowTemplate(templateData.value)
  emit('submit')
}

//流程的选项
let flowHandleOptions = ref([])

findUsers().then((res) => {
  flowHandleOptions.value = res.data?.data.map((opt) => {
    return {
      label: opt.nickname,
      value: opt.username
    }
  })
})

onMounted(() => {
  formEditorRef.value?.setData(templateData.value.formData)
})
</script>

<template>
  <div class="h-full">
    <el-space class="w-full" direction="vertical" fill>
      <el-card>
        <div class="flex">
          <span>模板名称：</span>
          <el-input v-model="templateData.name" />
          <el-button type="primary" @click="submitTemplate">保存模板</el-button>
        </div>
      </el-card>
      <el-card header="表单">
        <SytPageEditor ref="formEditorRef" @change="onFormEditorChange"></SytPageEditor>
      </el-card>
      <el-card header="流程">
        <SytFlow v-model="templateData.flowData" :flow-handle-options="flowHandleOptions" />
      </el-card>
    </el-space>
  </div>
</template>

<style scoped>
span {
  white-space: nowrap;
}
</style>
